//
//  UIViewController+NEDRouter.m
//  NEDRouter
//
//  Created by 98du on 2021/12/1.
//

#import "UIViewController+NEDRouterParame.h"
#import "UIViewController+NEDRouter.h"
#import <objc/runtime.h>
#import "NEDRouter.h"

@implementation UIViewController(NEDRouterParamePrivite)


-(NSDictionary *)ned_routerParams{
    return objc_getAssociatedObject(self, @selector(ned_routerParams));
}

-(void)setNed_routerParams:(NSDictionary *)ned_routerParams{
    objc_setAssociatedObject(self, @selector(ned_routerParams), ned_routerParams, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


/// 该控制器只能有一个， 如果已有则刷新该控制器数据 = 在当前的导航条中
- (UIViewController *(^)(void))ned_singletonAtNavigation{
    UIViewController *(^block)(void) = ^UIViewController *(void) {

        if(![self respondsToSelector:@selector(ned_routerIsSingletonAtNavigation)]){
            return self;
        }
        BOOL isSingleton = [self ned_routerIsSingletonAtNavigation];
        if(!isSingleton){
            return self;
        }
        
        NSDictionary * params = self.ned_routerParams;
        /// 需要跳转至的控制器
        __block UIViewController * popToExitVC = nil;
        __block UIViewController * popToExitFirstVC = nil;
        NSArray <UIViewController *> * viewControllers = NEDCurrentNavigationViewController().viewControllers;
        [viewControllers enumerateObjectsUsingBlock:^(UIViewController *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            void(^exitVCHandler)(UIViewController * singleVC) = ^(UIViewController * singleVC) {
                
                /// 新控制器的参数 在当前的同名控制器判断 是否需要做唯一处理
                if([singleVC respondsToSelector:@selector(ned_routerIsSingletonAtNavigationFiterWithParams:)]){
                    BOOL isSingleton = [singleVC ned_routerIsSingletonAtNavigationFiterWithParams:params];
                    if(isSingleton){
                        popToExitVC = singleVC;
                        *stop = YES;
                    }
                }else if(!popToExitFirstVC){
                    popToExitFirstVC = singleVC;
                }
            };
            
            if([obj isKindOfClass:NSClassFromString(@"RTContainerController")]){
                SEL cnSel = NSSelectorFromString(@"contentViewController");
                if([obj respondsToSelector:cnSel]){
                    UIViewController * contentViewController = [obj performSelector:cnSel];
                    if(contentViewController.class == self.class){
                        exitVCHandler(contentViewController);
                    }
                }
                if(obj.class == self.class){
                    exitVCHandler(obj);
                }
            }else if(obj.class == self.class){
                exitVCHandler(obj);
            }
            
            if([obj isEqual:viewControllers.lastObject] &&
               !popToExitVC &&
               popToExitFirstVC){
                popToExitVC = popToExitFirstVC;
            }
        }];
        
        if(popToExitVC){
            [NEDCurrentViewController().navigationController popToViewController:popToExitVC animated:YES];
            popToExitVC.ned_params(params);
            popToExitVC.ned_reloadViewContent();
            if([NEDRouter sharedManager].errorHandler){
                [NEDRouter sharedManager].errorHandler(NEDRouterErrorCodeControllerSingleton, [NSString stringWithFormat:@"已有该控制器:%@，不做跳转",self.class],@{@"className":NSStringFromClass(self.class)});
            }
            return nil;
        }
        return self;
    };
    return block;
}

/// 该控制器只能有一个， 如果已有则刷新该控制器数据 = 在keywindow中
- (UIViewController *(^)(void))ned_singletonAtWindow{
    UIViewController *(^block)(void) = ^UIViewController *(void) {
        if(![self.class respondsToSelector:@selector(ned_routerIsSingletonAtWindow)]){
            return self;
        }
        BOOL isSingleton = [self.class ned_routerIsSingletonAtWindow];
        if(!isSingleton){
            return self;
        }
        if(!self.isViewLoaded){
            return self;
        }
        if([self respondsToSelector:@selector(ned_routerNavigateToThisAppointAction)]){
            [self ned_routerNavigateToThisAppointAction];
        }
        self.ned_params(self.ned_routerParams);
        self.ned_reloadViewContent();
        return nil;
    };
    return block;
}

/// 该控制器需要登录操作
- (UIViewController *(^)(void))ned_needLogin{
    UIViewController *(^block)(void) = ^UIViewController *(void) {
        if([self respondsToSelector:@selector(ned_routerNeedLoginFirst)]){
            BOOL needLogin = [self ned_routerNeedLoginFirst];
            if(needLogin){
                if([NEDRouter sharedManager].errorHandler){
                    [NEDRouter sharedManager].errorHandler(NEDRouterErrorCodeNeedLogin, [NSString stringWithFormat:@"控制器:%@，需要先做登录操作",self.class],@{@"className":NSStringFromClass(self.class)});
                }
                return nil;
            }
        }
        return self;
    };
    return block;
}

@end



@implementation UIViewController (NEDRouterParame)


- (UIViewController *(^)(NSDictionary * params))ned_params{
    UIViewController *(^block)(NSDictionary * params) = ^UIViewController *(NSDictionary * params) {
        if(!params){
            return self;
        }
        if([self respondsToSelector:@selector(ned_routerLoadParams:)]){
            [self setNed_routerParams:params];
            [self ned_routerLoadParams:params];
        }
        return self;
    };
    return block;
}

- (UIViewController *(^)(void))ned_reloadViewContent{
    UIViewController *(^block)(void) = ^UIViewController *(void) {
        if(self.navigationController ||
           self.parentViewController ||
           self.presentingViewController ||
           [self isKindOfClass:[UITabBarController class]]){
            if([self respondsToSelector:@selector(ned_routerReloadViewContent)]){
                [self ned_routerReloadViewContent];
            }
        }
        return self;
    };
    return block;
}



@end

